package com.ant.storage.controller;

import com.ant.storage.common.ResultVo;
import com.ant.storage.pojo.Dictionary;
import com.ant.storage.pojo.OriginalData;
import com.ant.storage.service.ICategoryService;
import com.ant.storage.service.IDictionaryService;
import com.ant.storage.utils.ExcelDataProcessor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/filer")
@Api(tags = "文件上传接口")
public class FilerController {

    @Value("${file.upload-path}")
    private String uploadPath;

    @Value("${fileUrl.url}")
    private String fileUrl;

    @Autowired
    IDictionaryService dictionaryService;

    @Autowired
    ICategoryService categoryService;

    @ApiOperation(value = "上传图片")
    @PostMapping("/singleUpload")
    public ResultVo fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return ResultVo.success("请选择文件");
        }
        String str = savaFile(file);
        if (str != null) {
            String url = fileUrl + "/" + str;
            return ResultVo.success("上传成功", url);
        } else {
            return ResultVo.fail("上传失败");
        }
    }

    /**
     * 单个文件上传
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String savaFile(MultipartFile multipartFile) throws IOException {
        try {
            // 上传目录地址
            String uploadDir = uploadPath;
            // 如果目录不存在，自动创建文件夹
            System.out.println("uploadDir:" + uploadDir);
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //获取上传文件的后缀名
            String suffixName =
                    multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));
            // 获取上传文件的名称
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = uuid + suffixName;
            File newFile = new File(uploadDir + filename);
            // 完成文件上传
            try {
                multipartFile.transferTo(newFile);
                return filename;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "解析Excel")
    @PostMapping("/excelUpload")
    public ResultVo excelUpload() throws Exception {
        String name = "D:/tal/gm.xlsx";//D:\tal
        String fileName = "D:/tal/gm2.xlsx";//D:\tal
        // 1. 读取Excel数据（假设文件在resources目录下）
        List<OriginalData> categoryList = ExcelDataProcessor.processExcelData(fileName);
        categoryList.stream().forEach(item->{
            Dictionary dic=new Dictionary();
            dic.setParentId(item.getParentId());
            dic.setDicName(item.getCategoryName());
            dic.setDicValue(item.getCode());
            dic.setDicType("2");
            dictionaryService.save(dic);
        });

//        // 3. 保存到数据库
//        System.out.println("categoryList=>"+categoryList);
//        categoryService.saveBatch(categoryList);

        return ResultVo.fail("操作成功");
    }

    public static void main(String[] args) {
        try {
            String fileName = "D:/tal/gm2.xlsx";//D:\tal
            // 1. 读取Excel数据（假设文件在resources目录下）

            List<OriginalData> categoryList = ExcelDataProcessor.processExcelData(fileName);
            // 2. 整理数据为层级结构（code, name, parent_code）
            //  List<Category> categoryList = processData(originalDataList);
            System.out.println("整理后的数据行数：" + categoryList.size());
            System.out.println("整理后的数据行数：" + categoryList);
            // 3. 保存到数据库

            //saveToDatabase(categoryList);
            System.out.println("数据已成功保存到数据库！");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
